// 技能共享列表页面逻辑
const apiService = require('../../../js/services/api/sharedDatabaseService');

Page({
  data: {
    skillsList: [],
    categoryOptions: ['全部类别', '生活服务', '教育培训', '维修服务', '咨询服务', '其他技能'],
    selectedCategory: 0,
    serviceMethodOptions: ['全部方式', '线上服务', '线下服务', '两者皆可'],
    selectedServiceMethod: 0,
    page: 1,
    hasMore: true,
    loading: false
  },

  onLoad: function (options) {
    wx.setNavigationBarTitle({ title: '技能共享' });
    this.loadSkillsList();
  },

  onShow: function () {
    // 每次显示页面时都重新加载数据，确保数据是最新的
    this.loadSkillsList();
  },

  onPullDownRefresh: function () {
    this.refreshList();
  },

  onReachBottom: function () {
    if (this.data.hasMore && !this.data.loading) {
      this.loadMore();
    }
  },

  /**
   * 加载技能列表数据
   */
  async loadSkillsList() {
    if (this.data.loading) return;
    
    this.setData({ loading: true });
    
    try {
      // 构建查询参数
      const params = {
        page: this.data.page,
        category: this.data.selectedCategory > 0 ? this.data.categoryOptions[this.data.selectedCategory] : '',
        serviceMethod: this.getServiceMethodValue(this.data.selectedServiceMethod)
      };
      
      console.log('请求参数:', params);
      // 调用API获取真实数据
      const result = await apiService.getSkills(params);
      
      console.log('API返回结果:', result);
      
      // 验证API返回数据格式
      if (!result || !result.data || !Array.isArray(result.data.data)) {
        throw new Error('API返回数据格式不正确');
      }
      
      // 处理数据，添加serviceMethodText字段
      const processedData = result.data.data.map(item => ({
        ...item,
        serviceMethodText: this.getServiceMethodText(item.serviceMethod)
      }));
      
      this.setData({
        skillsList: this.data.page === 1 ? processedData : [...this.data.skillsList, ...processedData],
        hasMore: result.data.data.length > 0,
        loading: false
      });
      
      console.log('设置数据后skillsList长度:', this.data.skillsList.length);
    } catch (error) {
      console.error('获取技能列表失败:', error);
      // 请求失败时使用模拟数据
      const mockData = this.getMockSkillsData();
      console.log('使用模拟数据:', mockData);
      
      // 验证模拟数据格式
      if (!mockData || !Array.isArray(mockData.data)) {
        console.error('模拟数据格式不正确');
        this.setData({
          skillsList: [],
          hasMore: false,
          loading: false
        });
        wx.showToast({
          title: '数据加载失败',
          icon: 'none'
        });
        return;
      }
      
      // 处理模拟数据，添加serviceMethodText字段
      const processedMockData = mockData.data.map(item => ({
        ...item,
        serviceMethodText: this.getServiceMethodText(item.serviceMethod)
      }));
      
      this.setData({
        skillsList: processedMockData,
        hasMore: false,
        loading: false
      });
      wx.showToast({
        title: '网络请求失败，使用模拟数据',
        icon: 'none'
      });
    }
  },

  /**
   * 获取模拟技能数据
   */
  getMockSkillsData() {
    return {
      data: [
        {
          id: 1,
          name: '电脑维修',
          category: '维修服务',
          description: '提供电脑软硬件维修服务，经验丰富。',
          serviceMethod: 'offline',
          contactInfo: '135****5004',
          serviceTime: '工作日晚上和周末',
          price: '50-200元',
          experience: '5年维修经验',
          status: 'published',
          createTime: '2025-01-27'
        },
        {
          id: 2,
          name: '英语辅导',
          category: '教育培训',
          description: '英语专业毕业，可提供小学到高中英语辅导。',
          serviceMethod: 'both',
          contactInfo: '137****7005',
          serviceTime: '周末全天',
          price: '80-150元/小时',
          experience: '3年教学经验',
          status: 'published',
          createTime: '2025-01-27'
        },
        {
          id: 3,
          name: '手工编织',
          category: '生活服务',
          description: '擅长毛衣、围巾等编织，可教授编织技巧。',
          serviceMethod: 'offline',
          contactInfo: '134****4006',
          serviceTime: '每周三下午',
          price: '30-100元',
          experience: '10年编织经验',
          status: 'published',
          createTime: '2025-01-27'
        }
      ]
    };
  },

  /**
   * 加载模拟数据
   */
  loadMockData() {
    const mockData = this.getMockSkillsData();
    this.setData({
      skillsList: mockData.data,
      hasMore: false,
      loading: false
    });
  },

  /**
   * 获取服务方式值
   */
  getServiceMethodValue(index) {
    const methodMap = {
      1: 'online',
      2: 'offline', 
      3: 'both'
    };
    return methodMap[index] || '';
  },

  /**
   * 刷新列表
   */
  refreshList() {
    this.setData({ page: 1, hasMore: true });
    this.loadSkillsList();
    wx.stopPullDownRefresh();
  },

  /**
   * 加载更多
   */
  loadMore() {
    this.setData({ page: this.data.page + 1 });
    this.loadSkillsList();
  },

  /**
   * 选择类别
   */
  onCategoryChange(e) {
    const index = e.detail.value;
    this.setData({
      selectedCategory: index,
      page: 1,
      hasMore: true
    });
    this.loadSkillsList();
  },

  /**
   * 选择服务方式
   */
  onServiceMethodChange(e) {
    const index = e.detail.value;
    this.setData({
      selectedServiceMethod: index,
      page: 1,
      hasMore: true
    });
    this.loadSkillsList();
  },

  /**
   * 点击技能项
   */
  onSkillTap(e) {
    const skillId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/neighborhood-help/skill-sharing/detail?id=${skillId}`
    });
  },

  /**
   * 发布技能
   */
  onPublishSkill() {
    wx.navigateTo({
      url: '/pages/neighborhood-help/skill-sharing/publish'
    });
  },

  /**
   * 联系提供者
   */
  contactProvider(e) {
    const skill = e.currentTarget.dataset.skill;
    wx.showModal({
      title: '联系提供者',
      content: `确定要联系${skill.name}的提供者吗？\n联系方式: ${skill.contactInfo}`,
      success(res) {
        if (res.confirm) {
          // 这里可以实现拨打电话或发送消息的功能
          wx.makePhoneCall({
            phoneNumber: skill.contactInfo.replace(/\*+/g, ''),
            fail(err) {
              console.error('拨打电话失败:', err);
              wx.showToast({
                title: '拨打失败，请稍后重试',
                icon: 'none'
              });
            }
          });
        }
      }
    });
  },

  /**
   * 查看详情
   */
  viewSkillDetail(e) {
    const skillId = e.currentTarget.dataset.skill.id;
    wx.navigateTo({
      url: `/pages/neighborhood-help/skill-sharing/detail?id=${skillId}`
    });
  },

  /**
   * 获取服务方式文本
   */
  getServiceMethodText(method) {
    const methodMap = {
      'online': '线上服务',
      'offline': '线下服务',
      'both': '两者皆可',
      '线上': '线上服务',
      '线下': '线下服务',
      '线上线下均可': '两者皆可'
    };
    return methodMap[method] || method || '未知';
  }
});